package dmitrygusev.ratings.services;

import java.net.URL;
import java.util.List;

import org.apache.log4j.Logger;

import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

import dmitrygusev.ratings.model.Movie;
import dmitrygusev.ratings.utils.Config;

public abstract class AbstractSource {
	protected static final Logger logger = Logger.getLogger(AbstractSource.class);
    protected static final URLFetchService urlFetchService = URLFetchServiceFactory.getURLFetchService();
	protected static final Config config = new Config();

	protected static void addFirefoxDefaultHeaders(HTTPRequest request) {
		request.addHeader(new HTTPHeader("User-Agent", 
				"Mozilla/5.0 (Windows; U; Windows NT 6.0; ru; rv:1.9.1.1) Gecko/20090715 Firefox/3.5.1 (.NET CLR 3.5.30729)"));
		request.addHeader(new HTTPHeader("Accept", 
				"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
	}

	protected String queryHttp(String url, String responseEncoding, boolean followRedirects) {
		try {
			HTTPRequest request = new HTTPRequest(new URL(url), HTTPMethod.GET);
			if (! followRedirects) {
				request.getFetchOptions().doNotFollowRedirects();
			}
	        addFirefoxDefaultHeaders(request);

	        if (cookie != null) {
	        	request.addHeader(new HTTPHeader("Cookie", cookie));
	        }
	        
	        HTTPResponse response = urlFetchService.fetch(request);

			return new String(response.getContent(), responseEncoding);
		}
		catch (Exception e) {
			logger.error("Error querying url " + url + ": " + e);
		}
		
		return null;
	}

	protected String cookie;

	public abstract String getName();

	public abstract void fetchRawMovies(String query, List<Movie> result);

	protected abstract void fetchMovieDetails(Movie movie);
}
